/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.stylefeng.roses.seata.demo.business.modular;

import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.seata.demo.business.BusinessApplication.AccountService;
import cn.stylefeng.roses.seata.demo.business.BusinessApplication.OrderService;
import cn.stylefeng.roses.seata.demo.business.BusinessApplication.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 主控制器
 *
 * @author fengshuonan
 * @date 2021/8/29 11:13
 */
@RestController
public class HomeController {

    /**
     * 用户id
     */
    private static final String USER_ID = "U100001";

    /**
     * 商品编码
     */
    private static final String COMMODITY_CODE = "C00321";

    /**
     * 商品数量
     */
    private static final int ORDER_COUNT = 2;

    private final RestTemplate restTemplate;

    private final OrderService orderService;

    private final StorageService storageService;

    private final AccountService accountService;

    public HomeController(RestTemplate restTemplate, OrderService orderService,
                          StorageService storageService, AccountService accountService) {
        this.restTemplate = restTemplate;
        this.orderService = orderService;
        this.storageService = storageService;
        this.accountService = accountService;
    }

    /**
     * 测试seata分布式事务AT模式（rest方式）
     *
     * @author fengshuonan
     * @date 2021/8/29 11:14
     */
    @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx")
    @GetMapping(value = "/seata/rest", produces = "application/json")
    public ResponseData<?> rest() {

        // 远程调用，扣减商品库存
        ResponseData<?> result = restTemplate.getForObject("http://127.0.0.1:18082/storage/" + COMMODITY_CODE + "/" + ORDER_COUNT, ResponseData.class);

        // 调用不成功
        if (result == null || !"00000".equals(result.getCode())) {
            throw new RuntimeException();
        }

        // 远程调用，扣减订单
        String url = "http://127.0.0.1:18083/order";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("userId", USER_ID);
        map.add("commodityCode", COMMODITY_CODE);
        map.add("orderCount", ORDER_COUNT + "");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<ResponseData> response;
        try {
            response = restTemplate.postForEntity(url, request, ResponseData.class);
        } catch (Exception exx) {
            throw new RuntimeException("mock error");
        }
        result = response.getBody();

        if (result == null || !result.getCode().equals("00000")) {
            throw new RuntimeException();
        }

        return new SuccessResponseData<>();
    }

    /**
     * 测试seata分布式事务AT模式（feign方式）
     *
     * @author fengshuonan
     * @date 2021/8/29 11:14
     */
    @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx")
    @GetMapping(value = "/seata/feign", produces = "application/json")
    public ResponseData<?> feign() {

        ResponseData<?> result = storageService.storage(COMMODITY_CODE, ORDER_COUNT);

        if (result == null || !result.getCode().equals("00000")) {
            throw new RuntimeException();
        }

        result = orderService.order(USER_ID, COMMODITY_CODE, ORDER_COUNT);

        if (result == null || !result.getCode().equals("00000")) {
            throw new RuntimeException();
        }

        return new SuccessResponseData<>();
    }

    /**
     * 测试seata分布式事务TCC模式（feign方式）
     *
     * @author fengshuonan
     * @date 2021/8/29 11:14
     */
    @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-seata-tcc")
    @GetMapping(value = "/tcc/seata/feign", produces = "application/json")
    public ResponseData<?> feignTcc() {

        ResponseData<?> result = storageService.tccStorage(COMMODITY_CODE, ORDER_COUNT);

        if (result == null || !result.getCode().equals("00000")) {
            throw new RuntimeException();
        }

        result = accountService.tccAccount(USER_ID, ORDER_COUNT * 10);

        if (result == null || !result.getCode().equals("00000")) {
            throw new RuntimeException();
        }

        return new SuccessResponseData<>();
    }

}
